/**
 * @Author: oldTea
 * @CreateTime: 2024-11-26
 * @Description:
 * @Version: 1.0
 */
package com.ambition.demo.juc;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 *@Author: oldTea
 *@CreateTime: 2024-11-26
 *@Description:
 * CountDownLatch是一个Java并发工具，用于协调多线程同步，常用于主线程等待多个子线程完成任务后再执行。它基于AQS实现，
 * 计数器只能递减且不可重置。适用场景包括任务分解、并发请求处理、线程间依赖等。注意CountDownLatch的计数器不能增加，
 * 且异常处理要确保countDown()调用。
 *@Version: 1.0
 */
@Slf4j
public class CountDownLatchDemo {

    public static void main(String[] args) throws InterruptedException {
       // extracted();
        ExecutorService executor = Executors.newCachedThreadPool();
        CountDownLatch countDownLatch = new CountDownLatch(1000);
        ThreadUnsafeExample example = new ThreadUnsafeExample();

        for (int i = 0; i < 1000; i++) {
            executor.execute(() -> {
                example.add();
                countDownLatch.countDown();
            });
        }
        countDownLatch.await();
        System.out.println(example.get());
    }

    private static void extracted() throws InterruptedException {
        CountDownLatch latch = new CountDownLatch(3);
        Worker worker1 = new Worker("worker1",latch);
        Worker worker2 = new Worker("worker2",latch);
        Worker worker3 = new Worker("worker3",latch);


        worker1.start();
        worker2.start();
        worker3.start();

        //等待3秒后即使有线程未完成任务也继续向下执行
        latch.await(3, TimeUnit.SECONDS);
        log.info("所有任务执行完成");
    }

}


